import { ref, computed, type ComputedRef, reactive, toRef } from 'vue'

interface LoadParams {
  pageIndex: number
  pageSize: number
  [key: string]: any
}

const useLoadMore = (
  fn: (params: any) => Promise<any>,
  total: ComputedRef<number>,
  params: LoadParams
) => {
  //请求的参数，根据据变化的参数进行更新
  //const pageIndex = ref(params.pageIndex)
  //请求的参数，根据变化的参数进行更新
  // const requestParams = computed(() => {
  //   return { ...params, pageIndex: pageIndex.value + 1 }
  // })

  const requestParams = reactive(params)
  const loadMorePage = () => {
    requestParams.pageIndex++
    fn(requestParams)
  }
  const loadPrevPage = () => {
    requestParams.pageIndex--
    fn(requestParams)
  }

  const goToPage = (index: number) => {
    requestParams.pageIndex = index
    fn(requestParams)
  }

  const isFirstPage = computed(() => requestParams.pageIndex === 0)
  const totalPage = computed(() => Math.ceil(total.value / requestParams.pageSize))
  const isLastPage = computed(() => {
    return Math.ceil((total.value || 1) / requestParams.pageSize) === requestParams.pageIndex + 1
  })
  const pageIndex = toRef(requestParams, 'pageIndex')
  return {
    loadMorePage,
    isLastPage,
    isFirstPage,
    loadPrevPage,
    requestParams,
    pageIndex,
    goToPage,
    totalPage
  }
}
export default useLoadMore
